package com.jing.cloud.service.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.jing.cloud.service.api.constant.ApiErrCode;
import com.jing.cloud.service.api.util.ThreadLocalUtil;
import com.jing.cloud.service.user.bean.Ticket;
import com.jing.cloud.service.user.dao.TicketDao;
import com.jing.cloud.service.Res;
import com.jing.cloud.util.RspUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by 29017 on 2017/9/18.
 */
@Component
@Slf4j
public class TicketInterceptor extends HandlerInterceptorAdapter {

    private static final String HTTP_HEAD_TICKET_ATTR_STR = "Ticket";

    private static final List<String> whiteList = Lists.newArrayList();

    static {
        whiteList.add("/api/register");
        whiteList.add("/api/login");
        whiteList.add("/api/serverInfo");
    }

    @Autowired
    private TicketDao ticketDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (!whiteList.contains(uri)) {
            Res res = null;
            String ticketStr = request.getHeader(HTTP_HEAD_TICKET_ATTR_STR);
            if (null == ticketStr) {
                res = RspUtil.error(ApiErrCode.TICKET_NULL);
            } else {
                Ticket ticket = ticketDao.getByTicketStr(ticketStr);
                if (null == ticket) {
                    res = RspUtil.error(ApiErrCode.TICKET_NOT_EXIST);
                } else {
                    ThreadLocalUtil.setTicket(ticket);
                }
            }
            if (null != res) {
                response.getWriter().write(JSON.toJSONString(res));
                return false;
            }
        }


        return super.preHandle(request, response, handler);
    }
}
